<!DOCTYPE html>
<html>
	<head>
		 <meta charset="utf-8">
		<title>练习</title>
		<script src="js/d3.v4.min.js" charset="utf-8"></script>
	</head>
	<body>

		<script>
			var dataset=[150,220,360,450,110,130];
			//设置柱形图的参数
			var padding={left:20,top:20,right:20,bottom:20};
			var rectStep=25;
			var rectWidth=20;
			var height=600;
			var width=600;
			//创建画布
			var svg=d3.select("body")
					  .append("svg")
					  .attr("height",height)
					  .attr("width",width)

				
			//数据更新
			function draw(){			
				//分别获取矩形的update、enter、和exit的部分
				var rectUpdate=svg.selectAll("rect")
							  .data(dataset);
				var rectEnter=rectUpdate.enter();
				var rectExit=rectUpdate.exit();
				//分别获取文字的update、enter、和exit的部分
				var textUpdate=svg.selectAll("text")
							  .data(dataset);
				var textEnter=textUpdate.enter();
				var textExit=textUpdate.exit();
				
				//处理矩形的update、enter、和exit
				rectUpdate.attr("x",function(d,i){return padding.left+rectStep*i;})
						  .attr("y",function(d){return height-padding.bottom-d;})
						  .attr("height",function(d){return d;})
						  .attr("width",rectWidth)
						  .attr("fill","steelblue");
				rectEnter.append("rect")
						  .attr("x",function(d,i){return padding.left+rectStep*i;})
						  .attr("y",function(d){return height-padding.bottom-d;})
						  .attr("height",function(d){return d;})
						  .attr("width",rectWidth)
						  .attr("fill","steelblue");
				rectExit.remove();
				
				//处理文字的update、enter、和exit
				textUpdate.attr("x",function(d,i){return padding.left+rectStep*i;})
						  .attr("y",function(d){return height-padding.bottom-d;})
						  .attr("dy","1em")
						  .text(function(d){return d;})
						  .attr("font-size","14px");
				textEnter.append("text")
						  .attr("x",function(d,i){return padding.left+rectStep*i;})
						  .attr("y",function(d){return height-padding.bottom-d;})
						  .attr("dy","1em")
						  .text(function(d){return d;})
						  .attr("font-size","14px");
				textExit.remove();								
			}
			draw();
				function myadd(){
					dataset.push(Math.floor(Math.random()*400));
					draw();
				}
				function myascending(){
					
					dataset.sort(d3.ascending);
					draw();
				}
				function mydescending(){
					dataset.sort(d3.descending);
					draw();
				}
				function mydel(){
					 //splice函数三个参数：从索引的位置处，删除n个数，插入字符串，此处用法为删除最后一个数
					dataset.splice(dataset.length-1,1);
					draw();
				}
		</script>
		<button type="button" onclick="myadd()">增加数据</button>
		<button type="button" onclick="myascending()">升序数据</button>
		<button type="button" onclick="mydescending()">降序数据</button>
		<button type="button" onclick="mydel()">删除数据</button>	
	</body>
</html>
